import { useState, useMemo, useEffect } from 'react'
import Head from './Components/Head';
import Content from './Components/Content';
import Footer from './Components/Footer';
import useSessionStorage from '../utils/useSessionStorage.js'


import './App.css'

function App() {
/*   const [todoList, setTodoList] = useState([
    {
      id: 1,
      text: '学习vue',
      isChecked: true
    },
    {
      id: 2,
      text: '学习react',
      isChecked: false
    }
  ]); */

  const [todoList, setTodoList] = useState(useSessionStorage('todolist')||[]);


  const [status,setStatus] = useState('All')


  //改变单个todolis的选中状态
  function changeChecked(id, checked) {
    let newArr = todoList.map(item => {
      if (item.id == id) {
        //展开运算符后写的新值会把旧值替换掉！！！！！
        return { ...item, isChecked: checked }
      } else {
        return item
      }
    })
    setTodoList(newArr)
  }
  //删除某个todolis
  function deleteItem(id) {
    let newArr = todoList.filter(item => item.id != id)
    setTodoList(newArr)
  }
  //添加一条记录
  function addItem(val) {
    let newArr = [...todoList]
    newArr.push({
      id: Date.now(),
      text: val,
      isChecked: false,
    })
    setTodoList(newArr)

  }

  //计算属性，全选状态
  let computed = useMemo(() => {
    let flag = true
    todoList.forEach(item => {
      if (item.isChecked == false) {
        flag = false
      }
    })
    return flag
  }, [todoList])

    //计算属性，未完成数量
    let left = useMemo(() => {
      let num= todoList.filter(item=>item.isChecked==false).length
      return num
    }, [todoList])
    
    //确认修改
    function confirm(id,val){
      let newArr=[...todoList]
      newArr.forEach((item,index)=>{
        if(item.id==id){
          newArr[index].text=val  //这一步会修改原数组
        }
      })
      setTodoList(newArr)
    }

  //全选，全部取消
  function changeAllItems(e){
    let newArr=todoList
    newArr.forEach(item=>{
      item.isChecked=e
    })
    setTodoList([...newArr])
  }
  //切换状态
  function changeStatus(res){
    setStatus(res)
  }
    //计算属性，根据状态筛选内容
    let filterList = useMemo(() => {
      if(status=='All'){
        return todoList;
      }else if(status=='Active'){
        return todoList.filter(item=>item.isChecked==false)
      }else{
        return todoList.filter(item=>item.isChecked==true)
      }
    }, [status,todoList])
    //清除所有已完成的事项
    function clearAll(){
      let newArr=todoList.filter(item=>item.isChecked==false)
      setTodoList(newArr)
    }
    useEffect(()=>{
      useSessionStorage('todolist',todoList)
    },[todoList])
  return (
    <div className='todoapp'>
      <Head addItem={addItem} ></Head>
      <Content filterList={filterList}  todoList={todoList} changeChecked={changeChecked} deleteItem={deleteItem} computed={computed} changeAllItems={changeAllItems}  confirm={confirm}></Content>
      <Footer clearAll={clearAll} left={left} status={status} changeStatus={changeStatus}></Footer>
    </div>
  )
}

export default App
